package com.alax.interfaces.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alax.interfaces.domain.ApiCallRequest;
import com.alax.interfaces.service.IApiCallService;
import com.alax.common.core.domain.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Component
public class ApiAuthInterceptor implements HandlerInterceptor {
    
    @Autowired
    private IApiCallService apiCallService;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 构建API调用请求对象
        ApiCallRequest apiCallRequest = new ApiCallRequest();
        apiCallRequest.setAccessKey(request.getHeader("X-Access-Key"));
        apiCallRequest.setSignature(request.getHeader("X-Signature"));
        apiCallRequest.setTimestamp(Long.parseLong(request.getHeader("X-Timestamp")));
        apiCallRequest.setNonce(request.getHeader("X-Nonce"));
        
        // 2. 将请求对象存入请求上下文
        RequestContextHolder.currentRequestAttributes()
                .setAttribute("apiCallRequest", apiCallRequest, RequestAttributes.SCOPE_REQUEST);
        
        // 3. 验证API权限
        if (!apiCallService.checkApiPermission(apiCallRequest.getApiId(), apiCallRequest.getUserId())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(AjaxResult.error("API调用权限验证失败")));
            return false;
        }
        
        return true;
    }
} 